package com.mrd.util;

import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * 分页工具类，将分页组件中的过滤器转换为动态sql
 * 
 * @author han
 *
 */
public class JqgridFilterUtils {

  /**
   * 返回动态拼接Sql
   * 
   * @author han
   * @param filters
   * @return
   */
  public static String getSql(Filter filters, Class clas, String prefix) {
    String whereCase = "";
    String pre = "";
    if (StringUtils.isNotEmpty(prefix)) {
      pre = prefix;
    }
    if (filters != null && CollectionUtils.isNotEmpty(filters.getRules())) {
      for (SearchRule sr : filters.getRules()) {
        String field = sr.getField();
        Object data = sr.getData();
        boolean isDate = false;
        Field f = ReflectUtil.getField(sr.getField(), clas);
        if (f != null) {
          if (f.getType().equals(Date.class)) {
            data = "to_date('" + data + "','yyyy-MM-dd')";
            isDate = true;
          }
        }
        if (sr.getOp() == SearchRuleOption.eq) {
          whereCase = whereCase + " and " + pre + field + " ='" + data + "' ";
        } else if (sr.getOp() == SearchRuleOption.nc) {
          whereCase = whereCase + " and " + pre + field + " not in ('" + data + "') ";
        } else if (sr.getOp().equals(SearchRuleOption.gt)) {
          whereCase =
              whereCase + " and " + pre + field + (isDate ? " > " + data : " > '" + data + "'");
        } else if (sr.getOp().equals(SearchRuleOption.lt)) {
          whereCase =
              whereCase + " and " + pre + field + (isDate ? " < " + data : " < '" + data + "'");
        } else if (sr.getOp().equals(SearchRuleOption.ge)) {
          whereCase =
              whereCase + " and " + pre + field + (isDate ? " >= " + data : " >= '" + data + "'");
        } else if (sr.getOp().equals(SearchRuleOption.le)) {
          whereCase =
              whereCase + " and " + pre + field + (isDate ? " <= " + data : " <= '" + data + "'");
        } else {
          whereCase = whereCase + " and " + pre + field + " like '%" + data + "%' ";
        }
      }
    }
    return whereCase;
  }
}
